﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CommandLib.Base;
using System.Threading;
using System.Text.RegularExpressions;

namespace My12306
{
    public partial class UcYD : UserControl
    {
        public bool IsRun = false;
        private object m_lock = new object();
        private FrmMain frmMain;
        protected internal DataSetPiaoInfo dataSetPiaoInfo1;

        public UcYD()
        {
            InitializeComponent();
        }

        public UcYD(FrmMain frmMain)
        {
            this.InitializeComponent();
            this.frmMain = frmMain;
            this.cmbStart_time_str.SelectedIndex = 0;
        }


        /// <summary>
        /// GridView单元格单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (this.dataGridView1.Columns[e.ColumnIndex].DataPropertyName == "PostPar")
                {
                    DataSetPiaoInfo.DTCheCiRow dTCheCiRow = (this.bdscCheCi.Current as DataRowView).Row as DataSetPiaoInfo.DTCheCiRow;

                    if (dTCheCiRow.PostPar != "")
                    {
                        this.submutOrderRequest(dTCheCiRow.PostPar);
                    }
                    else
                    {
                        MessageBox.Show("当前车票不足", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                Log.WriteLog4Ex("dataGridView1_CellContentClick", ex);
            }
        }

        private void submutOrderRequest(string val)
        {
            if (string.IsNullOrEmpty(this.txtPassenger_1_cardno.Text))
            {
                MessageBox.Show("未填写身份证信息！", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            else
            {
                if (string.IsNullOrEmpty(this.txtPassenger_1_name.Text))
                {
                    MessageBox.Show("未填写乘车人姓名信息！", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
                else
                {
                    if (string.IsNullOrEmpty(this.txtPassenger_1_mobileno.Text))
                    {
                        MessageBox.Show("未填写乘车人手机信息！", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                    else
                    {
                        this.frmMain.ChangeState("预定中");
                        this.IsRun = true;
                        this.dataGridView1.Enabled = false;
                        new Thread(delegate()
                        {
                            try
                            {
                                string text = "";
                                int num = 3;
                                string text2 = null;
                                while (this.IsRun)
                                {
                                    if (num == 3)
                                    {
                                        text = this.frmMain.http.PostPage("https://dynamic.12306.cn/otsweb/order/querySingleAction.do?", val);
                                        while (this.frmMain.rexMang.IsMatch(text))
                                        {
                                            this.frmMain.WriteInfo("系统繁忙，正在重试！");
                                            this.frmMain.WriteHtml(text);
                                            text = this.frmMain.http.PostPage("https://dynamic.12306.cn/otsweb/order/querySingleAction.do?", val);
                                        }
                                        this.frmMain.WriteHtml(text);
                                        num = 1;
                                    }
                                    if (num == 1)
                                    {
                                        num = this.confirmPassengerAction(ref text, ref text2);
                                        if (num == 0 || num == 2)
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                this.frmMain.WriteInfo("确认车次发生错误，错误详细信息：" + ex.Message);
                                Log.WriteLog4Ex("submutOrderRequest", ex);
                            }
                            finally
                            {
                                this.BeginInvoke(
                                    (MethodInvoker)delegate()
                                    {
                                        this.dataGridView1.Enabled = true;
                                        MessageBox.Show("自动订票已停止，如未预定成功，请手动重试！", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                                    }
                                );
                                this.IsRun = false;
                                this.frmMain.ChangeState("待命");
                            }
                        }
                        )
                        {
                            IsBackground = true
                        }.Start();
                    }
                }
            }
        }

        private int confirmPassengerAction(ref string strhtml, ref string RandCode)
        {
            int result;
            try
            {
                Match bed_level_order_num = this.frmMain.regbed_level_order_num.Match(strhtml);
                Match cancel_flag = this.frmMain.regcancel_flag.Match(strhtml);
                Match end_time = this.frmMain.regend_time.Match(strhtml);
                Match from_station_name = this.frmMain.regfrom_station_name.Match(strhtml);
                Match from_station_telecode = this.frmMain.regfrom_station_telecode.Match(strhtml);
                Match id_mode = this.frmMain.regid_mode.Match(strhtml);
                Match seat_type_code = this.frmMain.regseat_type_code.Match(strhtml);
                Match start_time = this.frmMain.regstart_time.Match(strhtml);
                Match station_train_code = this.frmMain.regstation_train_code.Match(strhtml);
                Match ticket_type_order_num = this.frmMain.regticket_type_order_num.Match(strhtml);
                Match to_station_name = this.frmMain.regto_station_name.Match(strhtml);
                Match to_station_telecode = this.frmMain.regto_station_telecode.Match(strhtml);
                Match train_date = this.frmMain.regtrain_date.Match(strhtml);
                Match train_no = this.frmMain.regtrain_no.Match(strhtml);
                Match TOKEN = this.frmMain.regTOKEN.Match(strhtml);
                if (cancel_flag.Success && end_time.Success && from_station_name.Success && from_station_telecode.Success && id_mode.Success && seat_type_code.Success && start_time.Success && station_train_code.Success && ticket_type_order_num.Success && to_station_name.Success && to_station_telecode.Success && train_date.Success && train_no.Success && TOKEN.Success)
                {
                    bool flag = true;
                    string sttmp = RandCode;
                    bool sForce = false;
                    if (RandCode == null)
                    {
                        base.Invoke(
                            (MethodInvoker)delegate
                            {
                                FrmConfirm frmYDCfm = new FrmConfirm(this.frmMain);
                                frmYDCfm.ShowDialog();
                                flag = !frmYDCfm.IsCancel;
                                sttmp = frmYDCfm.txtCheckCode.Text.Trim();
                                sForce = frmYDCfm.chkSend100.Checked;
                            }
                        );
                    }
                    if (flag)
                    {
                        sForce = true;
                        string strUrl = "";
                        base.Invoke(
                            (MethodInvoker)delegate()
                            {
                                strUrl = string.Format("https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=confirmPassengerInfoSingle&checkbox9=Y&checkbox9=Y&checkbox9=Y&checkbox9=Y&checkbox9=Y&oldPassengers=&oldPassengers=&oldPassengers=&oldPassengers=&oldPassengers=&orderRequest.bed_level_order_num={0}&orderRequest.cancel_flag={1}&orderRequest.end_time={2}&orderRequest.from_station_name={3}&orderRequest.from_station_telecode={4}&orderRequest.id_mode={5}&orderRequest.reserve_flag={6}&orderRequest.seat_type_code={7}&orderRequest.start_time={8}&orderRequest.station_train_code={9}&orderRequest.ticket_type_order_num={10}&orderRequest.to_station_name={11}&orderRequest.to_station_telecode={12}&orderRequest.train_date={13}&orderRequest.train_no={14}&org.apache.struts.taglib.html.TOKEN={15}&passengerTickets={16},{17},{18},{19},{20},{21},Y&passenger_1_cardno={20}&passenger_1_cardtype={19}&passenger_1_mobileno={21}&passenger_1_name={18}&passenger_1_seat={16}&passenger_1_ticket={17}&randCode={22}&textfield=%E4%B8%AD%E6%96%87%E6%88%96%E6%8B%BC%E9%9F%B3%E9%A6%96%E5%AD%97%E6%AF%8D", new object[]
							    {
								    bed_level_order_num.Groups[1].Value, 
								    cancel_flag.Groups[1].Value, 
								    end_time.Groups[1].Value, 
								    from_station_name.Groups[1].Value, 
								    from_station_telecode.Groups[1].Value, 
								    id_mode.Groups[1].Value, 
								    "A", 
								    seat_type_code.Groups[1].Value, 
								    start_time.Groups[1].Value, 
								    station_train_code.Groups[1].Value, 
								    ticket_type_order_num.Groups[1].Value, 
								    to_station_name.Groups[1].Value, 
								    to_station_telecode.Groups[1].Value, 
								    train_date.Groups[1].Value, 
								    train_no.Groups[1].Value, 
								    TOKEN.Groups[1].Value, 
								    this.cmbPassenger_1_seat.SelectedValue, 
								    this.cmbPassenger_1_ticket.SelectedValue, 
								    this.txtPassenger_1_name.Text, 
								    this.cmbPassenger_1_cardtype.SelectedValue, 
								    this.txtPassenger_1_cardno.Text, 
								    this.txtPassenger_1_mobileno.Text, 
								    sttmp
							    });
                            }
                        );
                        RandCode = sttmp;
                        if (sForce)
                        {

                            new Thread(delegate()
                            {
                                try
                                {
                                    string strhtml2 = this.frmMain.http.PostPage(strUrl, "");
                                    lock (this.m_lock)
                                    {
                                        if (this.IsRun && this.JXConfirm(strhtml2) == 2)
                                        {
                                            this.IsRun = false;
                                        }
                                    }
                                }
                                catch (Exception ex2)
                                {
                                    Log.WriteLog4Ex("ForcePost", ex2);
                                }
                            }
                            )
                            {
                                IsBackground = true
                            }.Start();

                        }
                        strhtml = this.frmMain.http.PostPage(strUrl, "");
                        this.frmMain.WriteHtml(strhtml);
                        lock (this.m_lock)
                        {
                            if (this.IsRun)
                            {
                                result = this.JXConfirm(strhtml);
                                return result;
                            }
                        }
                    }
                }
                else
                {
                    this.frmMain.WriteInfo("未加载成功车次信息，已停止确认！");
                }
            }
            catch (Exception ex)
            {
                this.frmMain.WriteInfo("确认订单发生错误，已停止确认，错误详细信息：" + ex.Message);
                Log.WriteLog4Ex("确认订单错误", ex);
            }
            result = 0;
            return result;
        }
        private int JXConfirm(string strhtml)
        {
            Match match = this.frmMain.rexEx.Match(strhtml);
            int result;
            if (match.Success)
            {
                if (match.Groups[1].Value.Contains("稍后重试"))
                {
                    this.frmMain.WriteInfo("确认订单出错，错误信息：" + match.Groups[1].Value);
                    result = 1;
                    return result;
                }
                this.frmMain.WriteInfo("确认订单出错，已停止确认，错误信息：" + match.Groups[1].Value);
            }
            else
            {
                if (this.frmMain.rexSu.IsMatch(strhtml))
                {
                    base.BeginInvoke(
                        (MethodInvoker)delegate()
                        {
                            try
                            {
                                MessageBox.Show("预定可能已成功，请在浏览器中查看未完成订单信息完成支付！", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                                this.frmMain.Navigate("https://dynamic.12306.cn/otsweb/order/myOrderAction.do?method=queryMyOrderNotComplete&leftmenu=Y");

                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                                Log.WriteLog4Ex("预定成功", ex);
                            }
                        }
                    );

                    result = 2;
                    return result;
                }
                if (this.frmMain.rexMang.IsMatch(strhtml))
                {
                    this.frmMain.WriteInfo("系统繁忙，正在重试！");
                    result = 3;
                    return result;
                }
                this.frmMain.WriteInfo("未知状态，已停止确认！");
            }
            result = 0;
            return result;
        }

        private void GetYuPiao()
        {
            try
            {
                this.frmMain.ChangeState("获取余票中");
                Random random = new Random();
                string strdtTrain_date = null;
                string strcmbFrom_station_telecode = null;
                string strcmbTo_station_telecode = null;
                string strtxtTrain_no = null;
                string strcmbStart_time_str = null;
                base.Invoke(
                    (MethodInvoker)delegate()
                    {
                        strdtTrain_date = this.dtTrain_date.Value.ToString("yyyy-MM-dd");
                        strcmbFrom_station_telecode = this.cmbFrom_station_telecode.SelectedValue.ToString();
                        strcmbTo_station_telecode = this.cmbTo_station_telecode.SelectedValue.ToString();
                        strtxtTrain_no = this.txtTrain_no.Text;
                        strcmbStart_time_str = this.cmbStart_time_str.SelectedItem.ToString();
                    }
                );
                string hTML = this.frmMain.http.GetHTML(string.Format("https://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=queryLeftTicket&orderRequest.train_date={0}&orderRequest.from_station_telecode={1}&orderRequest.to_station_telecode={2}&orderRequest.train_no={3}&trainPassType=QB&trainClass=QB%23D%23Z%23T%23K%23QT%23&includeStudent=00&seatTypeAndNum=&orderRequest.start_time_str={4}&{5}", new object[]
				{
					strdtTrain_date, 
					strcmbFrom_station_telecode, 
					strcmbTo_station_telecode, 
					strtxtTrain_no, 
					strcmbStart_time_str, 
					random.NextDouble()
				}), "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                this.frmMain.WriteHtml(hTML);
                MatchCollection mths = this.frmMain.rexlst.Matches(hTML);
                base.Invoke(
                    (MethodInvoker)delegate()
                    {
                        this.dataSetPiaoInfo1.DTCheCi.Clear();
                        foreach (Match match in mths)
                        {
                            Match match2 = this.frmMain.rexFun.Match(match.Groups[23].Value);
                            string postPar;
                            if (match2.Success)
                            {
                                string arg_1D3_0 = "method=submutOrderRequest&arrive_time={0}&from_station_name={1}&from_station_telecode={2}&from_station_telecode_name={3}&include_student=00&lishi={4}&round_start_time_str={5}&round_train_date={6}&seattype_num=&single_round_type=1&start_time_str={5}&station_train_code={7}&to_station_name={8}&to_station_telecode={9}&to_station_telecode_name={10}&train_class_arr=QB%23D%23Z%23T%23K%23QT%23&train_date={11}&train_pass_type=QB&train_start_time={12}&trainno={13}&ypInfoDetail={14}";
                                object[] array = new object[15];
                                array[0] = match2.Groups[7].Value;
                                array[1] = match2.Groups[8].Value;
                                array[2] = match2.Groups[5].Value;
                                array[3] = match2.Groups[8].Value;
                                array[4] = match2.Groups[2].Value;
                                array[5] = this.cmbStart_time_str.SelectedItem;
                                object[] arg_112_0 = array;
                                int arg_112_1 = 6;
                                DateTime dateTime = DateTime.Now;
                                arg_112_0[arg_112_1] = dateTime.ToString("yyyy-MM-dd");
                                array[7] = match2.Groups[1].Value;
                                array[8] = match2.Groups[9].Value;
                                array[9] = match2.Groups[6].Value;
                                array[10] = match2.Groups[9].Value;
                                object[] arg_18D_0 = array;
                                int arg_18D_1 = 11;
                                dateTime = this.dtTrain_date.Value;
                                arg_18D_0[arg_18D_1] = dateTime.ToString("yyyy-MM-dd");
                                array[12] = match2.Groups[3].Value;
                                array[13] = match2.Groups[4].Value;
                                array[14] = match2.Groups[10].Value;
                                postPar = string.Format(arg_1D3_0, array);
                            }
                            else
                            {
                                postPar = "";
                            }
                            this.dataSetPiaoInfo1.DTCheCi.AddDTCheCiRow(match.Groups[1].Value, match.Groups[2].Value, match.Groups[5].Value.Replace("&nbsp;", ""), match.Groups[6].Value.Replace("&nbsp;", ""), match.Groups[9].Value.Replace("&nbsp;", ""), match.Groups[10].Value.Replace("&nbsp;", ""), match.Groups[11].Value, match.Groups[12].Value.Replace("<font color='#008800'>有</font>", "票量充足").Replace("<font color='darkgray'>无</font>", "无票"), match.Groups[13].Value.Replace("<font color='#008800'>有</font>", "票量充足").Replace("<font color='darkgray'>无</font>", "无票"), match.Groups[14].Value.Replace("<font color='#008800'>有</font>", "票量充足").Replace("<font color='darkgray'>无</font>", "无票"), match.Groups[15].Value.Replace("<font color='#008800'>有</font>", "票量充足").Replace("<font color='darkgray'>无</font>", "无票"), match.Groups[16].Value.Replace("<font color='#008800'>有</font>", "票量充足").Replace("<font color='darkgray'>无</font>", "无票"), match.Groups[17].Value.Replace("<font color='#008800'>有</font>", "票量充足").Replace("<font color='darkgray'>无</font>", "无票"), match.Groups[18].Value.Replace("<font color='#008800'>有</font>", "票量充足").Replace("<font color='darkgray'>无</font>", "无票"), match.Groups[19].Value.Replace("<font color='#008800'>有</font>", "票量充足").Replace("<font color='darkgray'>无</font>", "无票"), match.Groups[20].Value.Replace("<font color='#008800'>有</font>", "票量充足").Replace("<font color='darkgray'>无</font>", "无票"), match.Groups[21].Value.Replace("<font color='#008800'>有</font>", "票量充足").Replace("<font color='darkgray'>无</font>", "无票"), match.Groups[22].Value.Replace("<font color='#008800'>有</font>", "票量充足").Replace("<font color='darkgray'>无</font>", "无票"), postPar);
                        }
                    }
                );
            }
            catch (Exception ex)
            {
                this.frmMain.WriteInfo("获取余票信息发生错误，错误详细信息：" + ex.Message);
                Log.WriteLog4Ex("GetYuPiao", ex);
            }
            finally
            {
                base.BeginInvoke(
                    (MethodInvoker)delegate()
                    {
                        this.btnOK.Enabled = true;
                        MessageBox.Show("余票信息获取完成，如果存在车次信息，现在可点击[选这趟车]进行预定！", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                );
                this.frmMain.ChangeState("待命");
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (this.frmMain.IsLogin)
            {
                if (this.cmbFrom_station_telecode.SelectedIndex == -1)
                {
                    MessageBox.Show("发站必须填写！", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
                else
                {
                    if (this.cmbTo_station_telecode.SelectedIndex == -1)
                    {
                        MessageBox.Show("到站必须填写！", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                    else
                    {
                        if (this.cmbFrom_station_telecode.SelectedValue == this.cmbTo_station_telecode.SelectedValue)
                        {
                            MessageBox.Show("发到站不能一样！", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                        }
                        else
                        {
                            if (this.dtTrain_date.Value < DateTime.Today)
                            {
                                MessageBox.Show("日期不能小于今天！", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                            }
                            else
                            {
                                this.btnOK.Enabled = false;
                                new Thread(new ThreadStart(this.GetYuPiao))
                                {
                                    IsBackground = true
                                }.Start();
                            }
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("请先登录！", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
        }

        private void cmbFrom_station_telecode_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}
